/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.module.upms.model;

import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.lambkit.common.model.LambkitModel;
import com.lambkit.common.safe.JsoupFilter;
import com.lambkit.common.util.DateTimeUtils;
import com.lambkit.db.sql.column.Column;
import com.lambkit.module.upms.UpmsConfig;
import com.lambkit.module.upms.record.UpmsUser;
import com.lambkit.module.upms.row.IUpmsUser;
import com.lambkit.module.upms.server.service.UpmsServerApiService;
import com.lambkit.module.upms.server.service.UpmsUserModelService;
import com.lambkit.module.upms.server.service.impl.UpmsUserModelServiceImpl;
import com.lambkit.module.upms.sql.UpmsUserSqlBuilder;
import com.lambkit.web.LambkitControllerContext;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yangyong
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date 2022-03-01
 * @version 1.0
 * @since 1.0
 */
public class UpmsUserModel extends LambkitModel<UpmsUserModel> implements IUpmsUser<UpmsUserModel>  {

	private static final long serialVersionUID = 1L;

	private UpmsServerApiService getUpmsModelApiService() {
		return Lambkit.get(UpmsServerApiService.class);
	}

	public static UpmsUserModelService service() {
		return Lambkit.get(UpmsUserModelService.class, UpmsUserModelServiceImpl.class);
	}

	public static UpmsUserSqlBuilder sql() {
		return new UpmsUserSqlBuilder();
	}

	public static UpmsUserSqlBuilder sql(Column column) {
		UpmsUserSqlBuilder that = new UpmsUserSqlBuilder();
		that.add(column);
        return that;
    }

	public UpmsUserModel() {
		UpmsConfig config = Lambkit.config(UpmsConfig.class);
		String dbconfig = config.getDbconfig();
		if(StrKit.notBlank(dbconfig)) {
			this.use(dbconfig);
		}
	}

	public static UpmsUserModel create(UpmsUser bean) {
		UpmsUserModel model = new UpmsUserModel();
		model._setOrPut(bean.getColumns());
		return model;
	}

	public UpmsUser toPojo() {
		UpmsUser bean = new UpmsUser();
		bean.setColumns(this);
		return bean;
	}

	public static final String AVATAR_NO_AVATAR = "/lambkit/assets/upms/images/avatar.jpg";    // 刚注册时使用默认头像

	public static final int STATUS_REG = -1;	// 注册、未激活
	public static final int STATUS_OK = 0;		// 正常、已激活
	public static final int STATUS_LOCK_ID = 1;	// 锁定账号，无法做任何事情

	public boolean isStatusOk() {
		return getLocked() == STATUS_OK;
	}

	public boolean isStatusReg() {
		return getLocked() == STATUS_REG;
	}

	public boolean isStatusLockId() {
		return getLocked() == STATUS_LOCK_ID;
	}

	/**
	 * 过滤掉 nickName 中的 html 标记，恶意脚本
	 */
	protected void filter(int filterBy) {
		filterAccountNickName(this);
	}

	public UpmsUserModel removeSensitiveInfo() {
		remove("password", "salt");
		return this;
	}
	
	@Override
	public boolean save() {
		// TODO Auto-generated method stub
		if(getCtime()==null) {
			setCtime(DateTimeUtils.getCurrentTimeLong());
		}
		if(getPwLastTime()==null) {
			setPwLastTime(new Date());
		}
		boolean flag = super.save();
		if(flag) {
			HttpServletRequest request = LambkitControllerContext.get().getRequest();
			UpmsLogModel.service().addLog(getUsername(), "用户添加成功", "userAdd", String.valueOf(getUserId()), "userAdd", request);
		}
		return flag;
	}
	
	@Override
	public boolean update() {
		// TODO Auto-generated method stub
		boolean flag = super.update();
		if(flag) {
			HttpServletRequest request = LambkitControllerContext.get().getRequest();
			UpmsLogModel.service().addLog(getUsername(), "用户修改成功", "userUpdate", String.valueOf(getUserId()), "userUpdate", request);
		}
		return flag;
	}
	
	@Override
	public boolean delete() {
		// TODO Auto-generated method stub
		boolean flag = super.delete();
		if(flag) {
			HttpServletRequest request = LambkitControllerContext.get().getRequest();
			UpmsLogModel.service().addLog(getUsername(), "用户删除成功", "userDelete", String.valueOf(getUserId()), "userDelete", request);
		}
		return flag;
	}

	private void filterAccountNickName(UpmsUserModel account) {
		String nickName = account.getRealname();
		if (nickName != null) {
			account.setRealname(JsoupFilter.getText(nickName));
		}
	}

	/***
	 * 角色名称
	 * @return
	 */
	public String getRoleNames(){
		UpmsServerApiService upmsApiService = getUpmsModelApiService();
		List<UpmsRoleModel> upmsRoles = upmsApiService.selectUpmsRoleByUpmsUserId(getUserId());
		List<String> roles = new ArrayList<>();
		if(upmsRoles!=null) {
			for (int j = 0; j < upmsRoles.size(); j++) {
				UpmsRoleModel upmsRole =  upmsRoles.get(j);
				roles.add(upmsRole.getTitle());
			}
		}
		return roles == null ? "" : StringUtils.join(roles,",");
	}

	/***
	 * 角色id
	 * @return
	 */
	public String getRoles(){
		UpmsServerApiService upmsApiService = getUpmsModelApiService();
		List<UpmsRoleModel> upmsRoles = upmsApiService.selectUpmsRoleByUpmsUserId(getUserId());
		List<Long> roles = new ArrayList<>();
		if(upmsRoles!=null) {
			for (int j = 0; j < upmsRoles.size(); j++) {
				UpmsRoleModel upmsRole =  upmsRoles.get(j);
				roles.add(upmsRole.getRoleId());
			}
		}
		return roles == null ? "" : StringUtils.join(roles,",");
	}


	/***
	 * 组织名称
	 * @return
	 */
	public String getOrginName(){
		UpmsServerApiService upmsApiService = getUpmsModelApiService();
		List<UpmsOrganizationModel> upmsOrganizations = upmsApiService.selectUpmsOrganizationByUpmsUserId(getUserId());
		List<String> organNames = new ArrayList<>();
		if(upmsOrganizations!=null) {
			for (int i = 0; i < upmsOrganizations.size(); i++) {
				UpmsOrganizationModel upmsOrganization =  upmsOrganizations.get(i);
				organNames.add(upmsOrganization.getName());
			}
		}
		return organNames.size() == 0 ? "" :  StringUtils.join(organNames,",");
	}

	/***
	 * 组织ID
	 * @return
	 */
	public String getOrgs(){
		UpmsServerApiService upmsApiService = getUpmsModelApiService();
		List<UpmsOrganizationModel> upmsOrganizations = upmsApiService.selectUpmsOrganizationByUpmsUserId(getUserId());
		List<Long> organNames = new ArrayList<>();
		if(upmsOrganizations!=null) {
			for (int i = 0; i < upmsOrganizations.size(); i++) {
				UpmsOrganizationModel upmsOrganization =  upmsOrganizations.get(i);
				organNames.add(upmsOrganization.getOrganizationId());
			}
		}
		return organNames.size() == 0 ? "" :  StringUtils.join(organNames,",");
	}
}
